package com.ft.oa.service.impl;

import com.ft.oa.domain.dto.sys.SecurityUser;
import com.ft.oa.security.constant.SecurityConstant;
import com.ft.oa.service.sys.AuthorizeService;
import com.ft.oa.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Service("ss")
public class AuthorizeServiceImpl implements AuthorizeService {

    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean havePermission() {

        SecurityUser user = SecurityUtils.getCurrentUser();
        if(user.getRoles().contains(SecurityConstant.SUPER_ROLE)){
            //超级管理员拥有所有权限
            return true;
        }
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        HttpServletRequest request = requestAttributes.getRequest();

        String requestURI = request.getRequestURI();

        boolean present = user.getAuthorities().stream()
                .anyMatch(e -> {
                    boolean match = antPathMatcher.match(e.getAuthority(), requestURI);
                    return match;
                });

        return present;
    }
}
